package org.world.domain.aggregate.sheep;

import org.mc.ddd.infrastructure.util.ObjectConverter;
import org.springframework.stereotype.Service;
import org.world.domain.aggregate.animal.constant.GenderEnum;
import org.world.domain.aggregate.sheep.entity.Sheep;
import org.world.domain.aggregate.sheep.event.SheepCompletedGivingBirthEvent;
import org.world.domain.aggregate.sheep.event.SheepCreatedEvent;
import org.world.domain.aggregate.sheep.event.SheepGaveBirthEvent;

import javax.annotation.Resource;

@Service
public class SheepAggregate {
    @Resource
    private SheepRepository sheepRepository;

    public SheepCreatedEvent create(Sheep sheep) {
        sheepRepository.save(sheep);
        return ObjectConverter.convert(sheep, SheepCreatedEvent.class, (entity, event) -> {
            event.setSheepId(entity.getId());
        });
    }

    public SheepCompletedGivingBirthEvent completeGivingBirth(Sheep pregnantSheep) {
        pregnantSheep.setIsPregnant(false);

        sheepRepository.save(pregnantSheep);

        return new SheepCompletedGivingBirthEvent();
    }

    public SheepGaveBirthEvent newSheepBaby(Long motherSheepId, GenderEnum gender) {
        Sheep babySheep = new Sheep();
        babySheep.setMotherId(motherSheepId);
        babySheep.setGender(gender);
        babySheep.setIsPregnant(false);
        babySheep.setHasHorn(false);

        sheepRepository.save(babySheep);

        return new SheepGaveBirthEvent(babySheep.getId(), babySheep.getMotherId(), babySheep.getGaveBirthTime());
    }
}
